#include "mymovieapi.h"
#include "cfgfile.h"
#include "WS/ws.h" // get proxy
#include <QDebug>

MyMovieApi::MyMovieApi(QObject *parent) :
    QObject(parent)
{
}
MyMovieApi::MyMovieApi(const QString discId
                       ,bool includeAdult
                       ,bool includeEnglish
                       ,int locale
                       ,QObject *parent):
  QObject(parent)
  ,_discId(discId)
  ,_includeAdult(includeAdult)
  ,_includeEnglish(includeEnglish)
  ,_locale(locale)
{
    CFGFile cfg;
    //_endpoint = "http://127.0.0.1/workspace/PelicanoC/index.php?r=wsSettings/wsdl&ws=1";
    QString protocol("http://");
    QString endpoint = protocol+cfg.getServerIP()+":"+QString::number(cfg.getServerPort())+cfg.getServerPath()+"index.php?r=wsPelicanoC/wsdl&ws=1";
    _endpoint = new char[endpoint.size()+1];
    strcpy(_endpoint,endpoint.toStdString().c_str());

}
MyMovieApi::~MyMovieApi()
{
    if(_endpoint!=NULL)
    {
        delete _endpoint;
        _endpoint= NULL;
    }
}

void MyMovieApi::sendNewRippedDisc(QString id,QString path,QString discId,bool parentalControl)
{
    this->setTitleId(id);
    this->setPath(path);
    this->setDiscId(discId);
    this->addNewRippedDisc(parentalControl);
}
void MyMovieApi::requestIsAlreadyRipped(QString idMyMovie)
{
    if(isAlreadyRipped(idMyMovie))
    {
        emit alreadyRipped( idMyMovie );
    }
}

bool MyMovieApi::isAlreadyRipped(QString idMyMovie)
{
    qDebug() << "isAlreadyRipped(QString idMyMovie) "<<idMyMovie;
    WsPelicanoCControllerBinding wsp;
    wsp.endpoint = _endpoint;
    qDebug() << "EndPoint: "<<wsp.endpoint;
    bool response= false;

    int result = wsp.ns4__isAlreadyRipped(idMyMovie.toStdString(),response);

    if(result==SOAP_OK)
    {
        qDebug() << "is aready ripped";
        if(response)
        {
            qDebug() << "is aready ripped";
        }
    }
    else
    {
        qDebug() << "SOAP Error";
        soap_print_fault(wsp.soap, stderr);
    }
    return response;
}

void MyMovieApi::addNewRippedDisc(bool parentalControl)
{
    if(this->getTitleId()!="" &&this->getPath()!="")
    {
        WsPelicanoCControllerBinding wsp;
        wsp.endpoint = _endpoint;
        qDebug() << "EndPoint: "<<wsp.endpoint;
        bool response;
        std::string idMyMovie(this->getTitleId().toStdString());
        std::string newPath(this->getPath().toStdString());
        std::string discId(this->getDiscId().toStdString());

        qDebug() << "ns4__addNewRipMovie(idMyMovie,newPath,parentalControl,discId,response): "
            <<this->getTitleId()<<" "
            <<this->getPath()<<" "
            <<parentalControl<<" "
            <<this->getDiscId();
        int result = wsp.ns4__addNewRipMovie(idMyMovie,newPath,parentalControl,discId,response);

        if(result==SOAP_OK)
        {
            qDebug() << "send new disc OK";
        }
        else
        {
            qDebug() << "SOAP Error";
            soap_print_fault(wsp.soap, stderr);
        }
    }
}
void MyMovieApi::setPercentage(QString id,int percentage)
{
    WsPelicanoCControllerBinding wsp;
    wsp.endpoint = _endpoint;
    qDebug() << "EndPoint: "<<wsp.endpoint;
    bool response;
    std::string percent(QString::number(percentage).toStdString());
    std::string stdId(id.toStdString());

    int result = wsp.ns4__setPercentage(stdId, percent, response);

    if(result==SOAP_OK)
    {
        qDebug() << "setPercentage OK";
    }
    else
    {
        qDebug() << "SOAP Error";
        soap_print_fault(wsp.soap, stderr);
    }
}

DiscTitle MyMovieApi::loadDiscTitleById(QString id)
{
    MyMoviesWSSoap mmws;
    soap_ssl_init();
    if (soap_ssl_client_context(mmws.soap,
       SOAP_SSL_NO_AUTHENTICATION,
       NULL,
       NULL,
       NULL,
       NULL,
       NULL
    ))
    {
       soap_print_fault(mmws.soap, stderr);
    }
    _ns1__LoadDiscTitleById *request = new _ns1__LoadDiscTitleById;
    //std::string discId("679E43E9EC6AF8D2F627DD644A7AE74D2DAE80C5");
    Settings *settings = Settings::getInstance();
    std::string discId(id.toStdString());
    std::string empty;
    request->TitleId = &discId;
    request->Handshake = &empty;
    std::string name(settings->getMymoviesUsername().toStdString());
    request->UserName=&name;
    std::string passwd(settings->getMymoviesPassword().toStdString());
    request->Password=&passwd;
    request->Locale = _locale;
    request->Client = &empty;
    request->Version = &empty;

    _ns1__LoadDiscTitleByIdResponse *response = new _ns1__LoadDiscTitleByIdResponse;

    DiscTitle result;
    int soapResponse = mmws.__ns2__LoadDiscTitleById(request,response);
    if ( soapResponse== SOAP_OK)
    {
       QXmlInputSource inputSuorce;
       inputSuorce.setData(QString(response->LoadDiscTitleByIdResult->__any));
       qDebug()<<response->LoadDiscTitleByIdResult->__any;
       QXmlSimpleReader xmlReader;
       LoadDiscTitleByIdResponseParser handler;
       xmlReader.setContentHandler( &handler );
       if(xmlReader.parse( inputSuorce ))
       {
           qDebug() << "parsed OK";
           result = handler.getDiscTitle();
       }
       else
       {
           qDebug() << "parsed ERROR";
       }
   }
   else
   {
      soap_print_fault(mmws.soap, stderr);
   }
    delete request;
    delete response;
    return result;

}
QList<DiscData> MyMovieApi::searchDiscTitleByTitle(QString titleParam,QString countryParam, int  typeParam, int resultsParam,bool strictParam)
{
    MyMoviesWSSoap mmws;
    soap_ssl_init();
    if (soap_ssl_client_context(mmws.soap,
       SOAP_SSL_NO_AUTHENTICATION,
       NULL,
       NULL,
       NULL,
       NULL,
       NULL
    ))
    {
       soap_print_fault(mmws.soap, stderr);
    }
    _ns1__SearchDiscTitleByTitle *request = new _ns1__SearchDiscTitleByTitle;
    Settings *settings = Settings::getInstance();
    std::string name(settings->getMymoviesUsername().toStdString());
    request->UserName=&name;

    std::string passwd(settings->getMymoviesPassword().toStdString());
    request->Password=&passwd;
    request->IncludeAdult = _includeAdult;
    request->IncludeEnglish = _includeEnglish;
    request->Locale = _locale;
    std::string country(countryParam.toStdString());
    request->Country = &country;
    request->Results= resultsParam;
    std::string title(titleParam.toStdString());
    request->Title= &title;
    std::string type;
    if(typeParam==Blu_ray)
    {
        type="Blu-ray";
    }
    else
    {
        type="DVD";
    }
    request->Type= &type;
    request->Strict= strictParam;

    _ns1__SearchDiscTitleByTitleResponse *response = new _ns1__SearchDiscTitleByTitleResponse;

    QList<DiscData> result;
    QList<DiscData> resultAux;

    int soapResponse = mmws.__ns2__SearchDiscTitleByTitle(request,response);
    if ( soapResponse== SOAP_OK)
    {
       QXmlInputSource inputSuorce;
       inputSuorce.setData(QString(response->SearchDiscTitleByTitleResult->__any));
       qDebug()<<response->SearchDiscTitleByTitleResult->__any;
       QXmlSimpleReader xmlReader;
       MyMovieResponseParse handler;
       xmlReader.setContentHandler( &handler );
       if(xmlReader.parse( inputSuorce ))
       {
           qDebug() << "parsed OK";
       }
       else
       {
           qDebug() << "parsed ERROR";
       }
       resultAux =handler.getDiscDataList();
       QListIterator<DiscData> it(resultAux);
       while(it.hasNext())
       {
           DiscData item = it.next();
           item.alreadyRipped=isAlreadyRipped(item.id);
           DiscTitle discTitle= this->loadDiscTitleById(item.id);
           item.discTitle = discTitle;

           result.append(item);
       }
   }
   else
   {
      soap_print_fault(mmws.soap, stderr);
   }
    delete request;
    delete response;
    return result;

}

QList<MovieData> MyMovieApi::searchMyMovieIdByTitle(QString titleParam,QString countryParam,int typeParam, int resultsParam,bool strictParam)
{
    MyMoviesWSSoap mmws;
    soap_ssl_init();
    if (soap_ssl_client_context(mmws.soap,
       SOAP_SSL_NO_AUTHENTICATION,
       NULL,
       NULL,
       NULL,
       NULL,
       NULL
    ))
    {
       soap_print_fault(mmws.soap, stderr);
    }
    _ns1__SearchDiscTitleByTitle *request = new _ns1__SearchDiscTitleByTitle;
    //std::string discId("679E43E9EC6AF8D2F627DD644A7AE74D2DAE80C5");
    Settings *settings = Settings::getInstance();
    std::string name(settings->getMymoviesUsername().toStdString());
    request->UserName=&name;

    std::string passwd(settings->getMymoviesPassword().toStdString());
    request->Password=&passwd;
    request->IncludeAdult = _includeAdult;
    request->IncludeEnglish = _includeEnglish;
    request->Locale = _locale;
    std::string country(countryParam.toStdString());
    request->Country = &country;
    request->Results= resultsParam;
    std::string title(titleParam.toStdString());
    request->Title= &title;
    std::string type;
    if(typeParam==Blu_ray)
    {
        type="Blu-ray";
    }
    else
    {
        type="DVD";
    }
    request->Type= &type;
    request->Strict= strictParam;

    _ns1__SearchDiscTitleByTitleResponse *response = new _ns1__SearchDiscTitleByTitleResponse;

    QList<MovieData> result;
    QList<MovieData> resultAux;

    int soapResponse = mmws.__ns2__SearchDiscTitleByTitle(request,response);
    if ( soapResponse== SOAP_OK)
    {
       QXmlInputSource inputSuorce;
       inputSuorce.setData(QString(response->SearchDiscTitleByTitleResult->__any));
       qDebug()<<response->SearchDiscTitleByTitleResult->__any;
       QXmlSimpleReader xmlReader;
       MyMovieResponseParse handler;
       xmlReader.setContentHandler( &handler );
       if(xmlReader.parse( inputSuorce ))
       {
           qDebug() << "parsed OK";
       }
       else
       {
           qDebug() << "parsed ERROR";
       }
       resultAux =handler.getMovieDataList();
       QListIterator<MovieData> it(resultAux);
       while(it.hasNext())
       {
           MovieData item = it.next();
           item.alreadyRipped=isAlreadyRipped(item.id);
           result.append(item);
       }

   }
   else
   {
      soap_print_fault(mmws.soap, stderr);
   }
    delete request;
    delete response;
    return result;
}

QList<DiscData> MyMovieApi::getMyMovieId(QString paramDiscId)
{
    MyMoviesWSSoap mmws;
    soap_ssl_init();
    if (soap_ssl_client_context(mmws.soap,
       SOAP_SSL_NO_AUTHENTICATION,
       NULL,
       NULL,
       NULL,
       NULL,
       NULL
    ))
    {
       soap_print_fault(mmws.soap, stderr);
    }
    _ns1__SearchDiscTitleByDiscIds *request = new _ns1__SearchDiscTitleByDiscIds;
    //std::string discId("679E43E9EC6AF8D2F627DD644A7AE74D2DAE80C5");

    std::string discId(_discId.toStdString());
    if(paramDiscId!="")
        discId=paramDiscId.toStdString();
    request->DiscId = &discId;
    Settings *settings = Settings::getInstance();
    std::string name(settings->getMymoviesUsername().toStdString());
    request->UserName=&name;

    std::string passwd(settings->getMymoviesPassword().toStdString());
    request->Password=&passwd;
    request->IncludeAdult = _includeAdult;
    request->IncludeEnglish = _includeEnglish;
    request->Locale = _locale;
    _ns1__SearchDiscTitleByDiscIdsResponse *response = new _ns1__SearchDiscTitleByDiscIdsResponse;

    QList<DiscData> resultAux;
    QList<DiscData> result;

    int soapResponse = mmws.__ns2__SearchDiscTitleByDiscIds(request,response);
    if ( soapResponse== SOAP_OK)
    {
       QXmlInputSource inputSuorce;
       inputSuorce.setData(QString(response->SearchDiscTitleByDiscIdsResult->__any));
       qDebug()<<response->SearchDiscTitleByDiscIdsResult->__any;
       QXmlSimpleReader xmlReader;
       MyMovieResponseParse handler;
       xmlReader.setContentHandler( &handler );
       if(xmlReader.parse( inputSuorce ))
       {
           qDebug() << "parsed OK";
       }
       else
       {
           qDebug() << "parsed ERROR";
       }
       resultAux =handler.getDiscDataList();
       QListIterator<DiscData> it(resultAux);
       while(it.hasNext())
       {
           DiscData item = it.next();
           item.setDiscId(QString::fromStdString(discId));
           item.setAreadyRipped(isAlreadyRipped(item.getDiscId()));
           DiscTitle discTitle= this->loadDiscTitleById(item.getId());
           item.discTitle = discTitle;

           result.append(item);
       }
       this->_lastResponse=result;
    }
    else
    {
        soap_print_fault(mmws.soap, stderr);
    }
    delete request;
    delete response;
    return result;
}
void MyMovieApi::requestSearchDiscTitleByTitle(QString title,QString country, int  type, int results,bool strict)
{
    qDebug()<<"MyMovieApi::requestSearchDiscTitleByTitle(QString title,QString country, int  type, int results,bool strict)"<<title<<" "<<country<<" "<<type<<" "<<results<<" "<<strict;
    QList<DiscData> result = this->searchDiscTitleByTitle(QString("\"")+title+QString("\""),country,type,results,strict);
    if(result.count()>0)
        emit titleIdResponsed(result);
    else
        emit movieUnknown();
}

void MyMovieApi::requestMovieData(QString title,QString country, int  type, int results,bool strict)
{
    qDebug()<<"MyMovieApi::requestMovieData(QString title,QString country, int  type, int results,bool strict)"<<title<<" "<<country<<" "<<type<<" "<<results<<" "<<strict;
    QList<MovieData> result = this->searchMyMovieIdByTitle(QString("\"")+title+QString("\""),country,type,results,strict);
    qDebug()<<"requestMovieData emitting signal movieDataResponsed";
    if(result.count()>0)
        emit movieDataResponsed(result);
    else
        emit movieUnknown();
}

void MyMovieApi::requestTitleId(QByteArray paramDiscId)
{
    QList<DiscData> result = this->getMyMovieId(paramDiscId);
    if(result.count()>0)
    {
        qDebug()<<"titleIdResponsed(result) signal";
        emit titleIdResponsed(result);
    }
    else
    {
        qDebug()<<"titleIdUnknown() signal";
        emit titleIdUnknown();
    }
}

int MyMovieApi::getCurrentCommand(QString idDisc)
{
    WsPelicanoCControllerBinding wsp;
    wsp.endpoint = _endpoint;
    qDebug() << "EndPoint: "<<wsp.endpoint;
    std::string response;
    std::string stdIdDisc(idDisc.toStdString());

    int result = wsp.ns4__getCurrentCommand(stdIdDisc,response);

    if(result==SOAP_OK)
    {
        qDebug() << "SOAP getCurrentCommand OK";
    }
    else
    {
        qDebug() << "SOAP Error";
        soap_print_fault(wsp.soap, stderr);
    }
    QString qResult(response.c_str());
    qDebug() << "command: "<<qResult;
    return qResult.toInt();
}

QString MyMovieApi::setCurrentDiscIn(QString idDisc)
{
    WsPelicanoCControllerBinding wsp;
    wsp.endpoint = _endpoint;
    qDebug() << "EndPoint: "<<wsp.endpoint;
    std::string response;
    std::string stdIdDisc(idDisc.toStdString());

    int result = wsp.ns4__setCurrentDiscIn(stdIdDisc,response);

    if(result==SOAP_OK)
    {
        qDebug() << "SOAP setCurrentDiscIn OK";
    }
    else
    {
        qDebug() << "SOAP Error";
        soap_print_fault(wsp.soap, stderr);
    }
    return response.c_str();
}

bool MyMovieApi::setCurrentDiscOut(QString id)
{
    qDebug() << "MyMovieApi::setCurrentDiscOut(QString id): "<<id;
    WsPelicanoCControllerBinding wsp;
    wsp.endpoint = _endpoint;
    qDebug() << "EndPoint: "<<wsp.endpoint;
    bool response;
    std::string stdIdDisc(id.toStdString());

    int result = wsp.ns4__setCurrentDiscOut(stdIdDisc,response);

    if(result==SOAP_OK)
    {
        qDebug() << "SOAP setCurrentDiscOut OK";
    }
    else
    {
        qDebug() << "SOAP Error";
        soap_print_fault(wsp.soap, stderr);
    }
    qDebug() << "response: "<<response;
    return response;
}

void MyMovieApi::setPath(QString path)
{
    this->_path = path;
}
QString MyMovieApi::getPath()
{
    return _path;
}
void MyMovieApi::assignPath(QString path)
{
    this->setPath(path);
}
void MyMovieApi::setTitleId(QString titleId)
{
    _titleId = titleId;
}

QString MyMovieApi::getTitleId()
{
    return _titleId;
}
QString MyMovieApi::getDiscId()
{
    return _discId;
}
void MyMovieApi::setDiscId(QString value)
{
    _discId = value;
}

